import {
    createSlice,
    configureStore
} from "@reduxjs/toolkit";
import axios, {get} from "axios";
const userSlice = createSlice({
    name:"user",
    initialState:{
        userList:[]
    }
})
const goodsSlice = createSlice({
    name:"goods",
    initialState:{
        goodsList:[]
    },
    reducers:{
        addGoods(state,{payload}){
            state.goodsList = [
                ...state.goodsList,
                payload
            ]
        },
        upGoodsList(state,{payload}){
            state.goodsList = payload
        }
    }
})
const store = configureStore({
    reducer:{
        user:userSlice.reducer,
        goods:goodsSlice.reducer
    }
});
// console.log(store.getState().user.userList)
// action:同步（对象），异步（函数）
// store.dispatch({
//     type:"goods.js/addGoods",
//     payload:{
//         goodsName:"手机",
//         goodsPrice:100
//     }
// });
// store.dispatch({
//     type:"goods.js/addGoods",
//     payload:{
//         goodsName:"电脑",
//         goodsPrice:1000
//     }
// });
// console.log(goodsSlice.actions.addGoods());
// const {addGoods} = goodsSlice.actions;
// store.dispatch(addGoods({goodsName:"手机",goodsPrice:1}));
// store.dispatch(addGoods({goodsName:"电脑",goodsPrice:11}));

// 异步action
// 1
// const {upGoodsList} = goodsSlice.actions;
// axios.get("/data.json").then(value=>{
//     // console.log(value.data);
//     store.dispatch(upGoodsList(value.data.goodsList));
//     console.log(store.getState())
// })

// 2
// const {upGoodsList} = goodsSlice.actions;
// store.dispatch(async function(dispatch,getState){
//     const {data} = await axios.get("/data.json");
//     dispatch(upGoodsList(data.goodsList));
//     console.log(getState())
// })

// 3
// const {upGoodsList} = goodsSlice.actions;
// const asyncGetGoodsList = async function(dispatch,getState){
//     const {data} = await axios.get("/data.json");
//     dispatch(upGoodsList(data.goodsList));
//     console.log(getState())
// }
//
// store.dispatch(asyncGetGoodsList)

// 4
const {upGoodsList} = goodsSlice.actions;
const asyncGetGoodsList = function(a,b,c,d){
   return async function(dispatch,getState){
       const {data} = await axios.get("/data.json");
       dispatch(upGoodsList(data.goodsList));
       console.log(getState())
   }
}

store.dispatch(asyncGetGoodsList(1,2,3,4))